import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";

import router from "../router";
import config from "./config";
import { addLoading, delLoading } from "./loading";
import $store from "../store/index";

axios.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => response,
  error => Promise.resolve(error.response)
);

let apiHost = config.proxy.apiHost;

function checkStatus(response) {
  // 处理网络异常
  // if (true) {
  //   return Promise.reject("reject");
  // }
  if (!response) {
    Message.error("网络连接失败");
    return;
  }

  const { data, status } = response;
  if (status >= 500 && status <= 505) {
    Message.error("数据请求失败");
    return;
  }
  if (status === 200 || status === 304) {
    delLoading();
    return data;
  }
}

function checkCode(res) {
  const { code } = res;
  if (code === -40000 || code === -30001) {
    res.msg = "系统繁忙，请联系客服";
  }
  return res;
}

const post = (urls, val, dataType, responseType) => {
  let url = apiHost + "/" + urls;
  let jsons = {};
  let headerType;
  let dataVal;
  let urlArr = [
    "part/login/user",
    "part/login/code",
    "part/login/register",
    "part/login/password"
  ];

  if (!urlArr.includes(urls)) {
    if ($store.state._token) {
      jsons = {
        app_id: $store.state.app_id,
        _token: $store.state._token
      };
    } else {
      router.push({ path: "/login" });
      Message.error("登录已过期，请重新登录！");
    }
  }

  if (dataType === "FormData") {
    headerType = "multipart/form-data";
    dataVal = val;
  } else {
    headerType = "application/x-www-form-urlencoded";
    dataVal = { ...jsons, ...val };
    dataVal = qs.stringify(dataVal);
  }
  addLoading();
  return axios({
    method: "post",
    url,
    data: dataVal,
    responseType: responseType || "",
    timeout: 10000,
    headers: {
      "Content-Type": headerType
    },
    withCredentials: true
  })
    .then(checkStatus)
    .then(checkCode);
};
export default post;
